package com.tang.lts.core.support;

import com.tang.lts.core.factory.NameThreadFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Tang
 * @classname SystemClock
 * @description [  ]
 * @date 2022/5/15 16:21
 */
public class SystemClock {

    private final long period;
    private final AtomicLong now;

    private SystemClock(long period) {
        this.period = period;
        now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    private static class InstanceHodler{
        private static final SystemClock instance = new SystemClock(1);
    }

    private static SystemClock instance() {
        return InstanceHodler.instance;
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new NameThreadFactory("SystemClock", true));
        executorService.scheduleWithFixedDelay(() -> {
            now.set(System.currentTimeMillis());
        }, period, period, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis() {
        return now.get();
    }

    public static long now() {
        return instance().currentTimeMillis();
    }

}